import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/components/my_alert.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/common/utils/my_permission.dart';
import 'package:hxdj/home/home_viewmodel.dart';
import 'package:hxdj/home/recommend_technician/recommend_technician_page.dart';
import 'package:hxdj/home/technician_detail.dart/technician_detail_page.dart';
import 'package:hxdj/mine/member_center/member_center_page.dart';
import 'package:hxdj/recommend_project/recommend_project_viewmodel.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:provider/provider.dart';

class HomeRecommendWidget extends StatefulWidget {
  const HomeRecommendWidget({super.key});

  @override
  State<HomeRecommendWidget> createState() => _HomeRecommendWidgetState();
}

class _HomeRecommendWidgetState extends State<HomeRecommendWidget> {
  late HomeViewModel? viewModel;
  late MyGlobalViewModel? globalViewModel;

  @override
  void initState() {
    super.initState();
    viewModel = Provider.of<HomeViewModel>(context, listen: false);
    globalViewModel = Provider.of<MyGlobalViewModel>(context, listen: false);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: MyColours.materialBg,
        //设置四周圆角 角度
        borderRadius: BorderRadius.circular(12.5.w),
      ),
      margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.h),
      child: Column(
        children: [
          // hedaer
          _buildHeader(),

          Container(
            padding: EdgeInsets.only(left: 10.w, right: 10.w, bottom: 15.h),
            child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Expanded(
                flex: 1,
                child: SizedBox(
                  height: 224.h,
                  child: _buildRecommendPerson(),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  margin: EdgeInsets.only(left: 5.w),
                  height: 224.h,
                  child: Column(
                    children: [
                      Expanded(
                          flex: 123,
                          child: Row(
                            children: [
                              _buildMoreProject(),
                              SizedBox(width: 5.w),
                              _buildCheckin(),
                            ],
                          )),
                      Expanded(flex: 100, child: _buildVip()),
                    ],
                  ),
                ),
              ),
            ]),
          ),
        ],
      ),
    );
  }

  //header
  _buildHeader() {
    return Container(
        padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h, bottom: 15.h),
        child: Row(children: [
          //标题
          Expanded(
            child: Container(
              alignment: Alignment.centerLeft,
              child: Column(
                children: [
                  MyText("今日推荐", textStyle: MyTextStyles.textBlackBold16),
                  const MyBorder(
                      color: MyColours.appMain,
                      backgroundColor: MyColours.appMain,
                      radius: 1.5,
                      child: SizedBox(
                        width: 25,
                        height: 3,
                      ))
                ],
              ),
            ),
          ),
          const Spacer(),

          //更多
          MyTapWidget(
            onTap: () {
              NavigatorUtils.push(context, RecommendTechnicianPage.routeName);
            },
            child: Row(
              children: [
                //更多
                MyText("更多推荐", color: MyColours.color999999, fontSize: 11.sp),
                //箭头
                Container(
                    padding: EdgeInsets.only(left: 5.w),
                    child: const MyImage(
                      imageName: "ic_arrow_right",
                      width: 5,
                      height: 8,
                    )),
              ],
            ),
          ),
        ]));
  }

  //更多项目
  _buildMoreProject() {
    if (viewModel == null) return Container();
    ProjectModel? projectModel = viewModel?.projectModel;

    return Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () {
          globalViewModel?.setIndex(1);
        },
        child: MyBorder(
          decoration: MyBorder.defaultDecoration,
          radius: 11.w,
          child: Column(
            children: [
              ClipRRect(
                  //圆角图片
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(11.0.w), topRight: Radius.circular(11.0.w)),
                  child: MyCachedNetworkImage(
                    imageUrl: projectModel?.logo ?? "",
                    height: 98.h,
                    fit: BoxFit.cover,
                  )),
              Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(top: 6.w, bottom: 6.h),
                  child: MyText(
                    "更多项目",
                    fontSize: 10.sp,
                    color: MyColours.text,
                  )),
            ],
          ),
        ),
      ),
    );
  }

  //技师入住
  _buildCheckin() {
    return Expanded(
        flex: 1,
        child: GestureDetector(
          onTap: () async {
            String qrCode = await viewModel!.requestTechnicianCheckIn();
            if (qrCode.isNotEmpty) {
              MyAlertManager.showAlert(AlertType.customWidget, context, "", "",
                  child: _buildTechnicianCheckInQrCode(qrCode));
            }
          },
          child: SizedBox(
            height: 123.h,
            child: MyBorder(
              decoration: MyBorder.defaultDecoration,
              radius: 11.w,
              child: Column(
                children: [
                  ClipRRect(
                      //圆角图片
                      borderRadius:
                          BorderRadius.only(topLeft: Radius.circular(11.0.w), topRight: Radius.circular(11.0.w)),
                    child: MyImage(
                      imageName: "ic_jishi",
                      height: 98.h,
                      boxFit: BoxFit.fitHeight,
                    ),
                  ),
                  //  MyCachedNetworkImage(
                  //   imageUrl: "https://picsum.photos/800/600?t=1233}",
                  //   height: 98.h,
                  //   fit: BoxFit.cover,
                  // )),
                  Container(
                      padding: EdgeInsets.only(top: 6.w, bottom: 6.h),
                      child: MyText(
                        "技师入住",
                        fontSize: 10.sp,
                        color: MyColours.text,
                      )),
                ],
              ),
            ),
          ),
        ));
  }

  _buildVip() {
    return Consumer(builder: (context, MyGlobalViewModel globalViewModel, child) {
      return Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(top: 5.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(11.w),
          gradient: const LinearGradient(
            colors: [Color.fromRGBO(61, 198, 148, 0.2), Color.fromRGBO(61, 198, 148, 0.1)],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
        ),
        child: Stack(
          children: [
            //vip信息
            _buildVipInfo(),
            Positioned(bottom: 0, right: 0, child: _buildVipButton())
          ],
        ),
      );
    });
  }

  //vip信息
  _buildVipInfo() {
    return MyTapWidget(
      onTap: () {
        NavigatorUtils.push(context, MemberCenterPage.routeName).then((value) {
          //刷新下用户信息
          debugPrint("刷新下用户信息");
        });
      },
      child: Container(
        margin: EdgeInsets.only(left: 10.w, top: 10.h),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MyClipRect(imageUrl: globalViewModel?.userModel?.picUrl ?? "", width: 30.w, height: 30.w, radius: 15.w),
            Container(
              padding: const EdgeInsets.only(left: 3, top: 3),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  MyText(
                    globalViewModel?.userModel?.nickName ?? "",
                    color: MyColours.text,
                    fontSize: 10.sp,
                    fontWeight: FontWeight.w600,
                  ),
                  MyText(
                    globalViewModel?.userDetailModel?.userData?.isVip == 1
                        ? "${globalViewModel?.userDetailModel?.userData?.vipEndTime ?? ""}到期"
                        : "暂未开通会员",
                    fontSize: 8.sp,
                    color: MyColours.text,
                    // fontWeight: FontWeight.w500,
                  ),
                ],
              ),
            ),
            const Spacer(),
            Padding(
              padding: EdgeInsets.only(right: 10.w, top: 7.h),
              child: const MyImage(imageName: "ic_home_vip", width: 40, height: 15),
            ),
          ],
        ),
      ),
    );
  }

  //推荐人员
  _buildRecommendPerson() {
    if (viewModel == null) return Container();
    if (viewModel?.technicianModel == null) return Container();

    NearbyTechnicianModel? technicianModel = viewModel?.technicianModel;

    List<String>? imgs = technicianModel?.imgs?.split(",") ?? [""];
    return MyTapWidget(
      onTap: () {
        NavigatorUtils.pushParams(context, "${TechnicianDetailPage.routeName}?tId=${technicianModel?.id}");
      },
      child: MyBorder(
          radius: 11.w,
          decoration: MyBorder.defaultDecoration,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //图片
              ClipRRect(
                  //圆角图片
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(11.0.w), topRight: Radius.circular(11.0.w)),
                  child: MyCachedNetworkImage(
                    imageUrl: imgs.first,
                    fit: BoxFit.cover,
                    width: 167.w,
                    height: 164.h,
                  )),

              //标题
              Container(
                padding: EdgeInsets.only(left: 7.w, top: 9.h),
                child: Text(technicianModel?.desc ?? "",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyColours.textBlack, fontSize: 12.sp)),
              ),

              Container(
                  padding: EdgeInsets.only(left: 7.w, top: 13.h, right: 7.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      MyText(technicianModel?.name ?? "",
                          color: MyColours.textGray, fontSize: 11.sp, fontWeight: FontWeight.w600),
                      const Spacer(),
                      Container(
                        padding: EdgeInsets.only(right: 7.w),
                        child: Row(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(right: 5.w),
                              child: const MyImage(
                                imageName: "ic_distance",
                                width: 10,
                                height: 12.5,
                              ),
                            ),
                            MyText(technicianModel?.distanceStr ?? "", color: MyColours.textGray, fontSize: 11.sp),
                          ],
                        ),
                      )
                    ],
                  )),
            ],
          )),
    );
  }

  //开通按钮
  _buildVipButton() {
    return Container(
      margin: EdgeInsets.only(right: 10.w, bottom: 10.w),
      child: MyBorder(
        backgroundColor: MyColours.appMain.withOpacity(0.5),
        radius: 14,
        color: MyColours.appMain.withOpacity(0.5),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 13.w, vertical: 4.w),
          child: MyText(
            globalViewModel?.userDetailModel?.userData?.isVip == 1 ? "立即续费" : "立即开通会员",
            fontSize: 7.sp,
            color: MyColours.text,
            fontWeight: FontWeight.w200,
          ),
        ),
      ),
    );
  }

//技师入住
  _buildTechnicianCheckInQrCode(String qrCode) {
    GlobalKey globalKey = GlobalKey();
    return Container(
        decoration: BoxDecoration(
            color: MyColours.materialBg,
            //设置四周圆角 角度
            borderRadius: BorderRadius.circular(30.w)),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          SizedBox(height: 30.h),
          RepaintBoundary(
              key: globalKey,
              child: Container(
                  decoration: BoxDecoration(
                      color: MyColours.bgColor,

                      //设置四周圆角 角度
                      borderRadius: BorderRadius.circular(10.w)),
                  child: MyCachedNetworkImage(imageUrl: qrCode, width: 140.w))),
          Padding(
            padding: EdgeInsets.only(top: 15.w, bottom: 40.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyTapWidget(
                  onTap: () {
                    saveScreenshot(globalKey);
                  },
                  child: Column(
                    children: [
                      MyImage(imageName: "ic_save_photo", width: 42.w),
                      Padding(
                        padding: EdgeInsets.only(top: 10.w),
                        child: const MyText("保存到相册", color: MyColours.color4F4B46, fontSize: 14),
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ]));
  }

  //保存图
  Future<Uint8List?> takeScreenshot(GlobalKey globalKey) async {
    try {
      RenderRepaintBoundary boundary = globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = (await boundary.toImage(pixelRatio: 3.0)); // 调整分辨率以适应高像素密度设备
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      if (byteData != null) {
        Uint8List pngBytes = byteData.buffer.asUint8List();
        return pngBytes;
      }
    } catch (e) {
      return null;
    }
    return null;
  }

  saveScreenshot(GlobalKey globalKey) async {
    Uint8List? screenshotBytes = await takeScreenshot(globalKey);
    if (screenshotBytes != null) {
      //获取保存图片的权限
      // ignore: use_build_context_synchronously
      bool permission = await MyPermission.requestPermission(context);
      if (permission) {
        final result = await ImageGallerySaver.saveImage(screenshotBytes);
        debugPrint('result= $result'); // 打印保存结果
        EasyLoading.showSuccess("已保存到本地");
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
    } else {
      EasyLoading.showError("保存失败");
    }
  }
}
